package com.zhang.third.day09;

import com.zhang.third.utils.Event;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;

/**
 * @title: 使用底层api实现订单超时--解决乱序问题
 * @author: zhang
 * @date: 2022/4/13 13:52
 */
public class Example3_1 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        SingleOutputStreamOperator<String> result = env
                .fromElements(
                        new Event("order-1", "create", 1000L),
                        new Event("order-2", "create", 2000L),
                        new Event("order-3", "pay", 9000L),
                        new Event("order-3", "create", 3000L),
                        new Event("order-1", "pay", 4000L)
                )
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy.<Event>forBoundedOutOfOrderness(Duration.ofSeconds(6))
                                .withTimestampAssigner(new SerializableTimestampAssigner<Event>() {
                                    @Override
                                    public long extractTimestamp(Event element, long recordTimestamp) {
                                        return element.ts;
                                    }
                                })
                )
                .keyBy(r -> r.key)
                .process(new KeyedProcessFunction<String, Event, String>() {
                    private ValueState<Event> orderState;
                    private ValueState<Event> payState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        orderState = getRuntimeContext().getState(
                                new ValueStateDescriptor<Event>(
                                        "order-state",
                                        Types.POJO(Event.class)
                                )
                        );

                        payState = getRuntimeContext().getState(
                                new ValueStateDescriptor<Event>(
                                        "pay-state",
                                        Types.POJO(Event.class)
                                )
                        );
                    }

                    @Override
                    public void processElement(Event value, KeyedProcessFunction<String, Event, String>.Context ctx, Collector<String> out) throws Exception {
                        if (value.value.equals("create")) {
                            if (payState.value() == null) {
                                orderState.update(value);
                                ctx.timerService().registerEventTimeTimer(value.ts + 5000L);
                            } else {
                                out.collect("订单" + value.key + "正常支付，订单创建的时间是：" +
                                        "" + value.ts + "；订单支付时间是：" + payState.value().ts);
                                payState.clear();
                            }
                        } else if (value.value.equals("pay")) {
                            if (orderState.value() == null) {
                                //由于网络传输，创建订单数据晚到
                                payState.update(value);
                                ctx.timerService().registerEventTimeTimer(ctx.timerService().currentWatermark() + 5000L);
                            } else {
                                out.collect("订单" + value.key + "正常支付，订单创建的时间是：" +
                                        "" + orderState.value().ts + "；订单支付时间是：" + value.ts);
                                orderState.clear();
                            }
                        }
                    }

                    @Override
                    public void onTimer(long timestamp, KeyedProcessFunction<String, Event, String>.OnTimerContext ctx, Collector<String> out) throws Exception {
                        if (orderState.value() != null) {
                            ctx.output(new OutputTag<String>("timeout") {
                            }, "订单" + orderState.value().key + "在5秒钟之内未支付");
                            orderState.clear();
                        }
                        if (payState.value()!=null){
                            ctx.output(new OutputTag<String>("Payed TimerOut or No Create") {
                            }, payState.value().key + " Payed But No Create");
                            payState.clear();
                        }
                    }
                });

        result.getSideOutput(new OutputTag<String>("timeout") {
        }).print("侧输出流1");
        result.getSideOutput(new OutputTag<String>("Payed TimerOut or No Create") {
        }).print("侧输出流2");
        result.print("主流");

        env.execute();
    }
}
